package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.consumer.config.ServerIpPortProperties;
import com.lagou.rpc.consumer.zk.ConsumerZk;
import com.lagou.rpc.consumer.zk.RequestMsgContainer;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
@Component
public class RpcClientProxy {

    @Autowired
    private ConsumerZk consumerZk;

    @Autowired
    private ServerIpPortProperties properties;

    public Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);

                        // todo: 从集合中取出netty客户端连接(在此之前需要判断负载均衡)
                        // 2.获取provider下所有子节点
                        CuratorFramework zkClient = consumerZk.getZkClient();
                        List<String> strings = zkClient.getChildren().forPath("/provider");
                        List<String> shortList = new ArrayList<>();
                        long shortTime = Long.MAX_VALUE;
                        // 2.1先找到最短的时间
                        for (String s : strings) {
                            String path = "/provider/" + s;
                            String dataJson = new String(zkClient.getData().forPath(path));
                            JSONObject jsonObject = JSONObject.parseObject(dataJson);
                            long usedTime = Long.parseLong(String.valueOf(jsonObject.get("usedTime")));
                            shortTime = Math.min(shortTime, usedTime);
                        }
                        // 2.2根据最短时间获取到符合条件的节点
                        for (String s : strings) {
                            String path = "/provider/" + s;
                            String dataJson = new String(zkClient.getData().forPath(path));
                            JSONObject jsonObject = JSONObject.parseObject(dataJson);
                            long usedTime = Long.parseLong(String.valueOf(jsonObject.get("usedTime")));
                            if(usedTime == shortTime){
                                // 记录耗时最短的所有节点
                                shortList.add(path);
                            }
                        }
                        // 2.3如果shortList大小大于1，那么随机获取一个节点
                        RpcClient rpcClient = null;
                        String shortPath = "";
                        if(shortList.size() == 1){
                            shortPath = shortList.get(0);
                            rpcClient = consumerZk.getMap().get(shortPath);
                        }else if(shortList.size() > 1){
                            Random random = new Random();
                            int i = random.nextInt(shortList.size());
                            shortPath = shortList.get(i);
                            rpcClient = consumerZk.getMap().get(shortPath);
                        }

                        try {
                            String s = new String(zkClient.getData().forPath(shortPath));
                            JSONObject jsonObject1 = JSONObject.parseObject(s);
                            System.out.println("客户端负载均衡到：" + jsonObject1.get("ip") + ":" + jsonObject1.get("port"));

                            //3.发送消息
                            long startTime = System.currentTimeMillis();
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            long endTime = System.currentTimeMillis();
                            // 记录请求耗时和当前时间,存放在内存中
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("usedTime", endTime - startTime); // 请求耗时
                            jsonObject.put("requestTime", System.currentTimeMillis()); // 当前请求时间
                            RequestMsgContainer.getMap().put(shortPath, jsonObject.toJSONString());

                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            //rpcClient.close();
                        }

                    }
                });
    }
}
